package org.mzyyn.qr.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.mzyyn.qr.config.ApplicationContextHelper;
import org.mzyyn.qr.constants.AppletsApiUrlMapping;
import org.mzyyn.qr.constants.RedisKeyAppletsConstant;
import org.mzyyn.qr.constants.UserConstant;
import org.mzyyn.qr.context.UserAuthContext;
import org.mzyyn.qr.entity.AppManagerPO;
import org.mzyyn.qr.filter.RequestWrapper;
import org.mzyyn.qr.service.AppManagerService;
import org.mzyyn.qr.util.HttpUtil;
import org.mzyyn.qr.util.ServletUtil;
import org.mzyyn.qr.vo.user.UserInfoRes;
import org.qr.xiaocao.common.enums.CommonResultEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;


/**
 * @author lipeng
 * @description
 * @date 2024/01/17
 */
@Slf4j
@Component
public class AppletsInterceptor implements HandlerInterceptor {

    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        if (request instanceof RequestWrapper) {
            String requestBody = ((RequestWrapper) request).getBody();
            log.info("请求参数：{}",requestBody);
        }

        String requestURI = request.getRequestURI();
        if(requestURI.equals(AppletsApiUrlMapping.SETTING_SPECIAL_GET)
                || requestURI.equals(AppletsApiUrlMapping.SETTING_SPECIAL_SAVE)
        ){
            return true;
        }

        //通过appid来区分是什么平台
        String appid = ServletUtil.getHeader(UserConstant.APPID);
        AppManagerService appManagerService = ApplicationContextHelper.getBean(AppManagerService.class);
        AppManagerPO appManager = appManagerService.getAppManagerByAppId(appid);
        if( null == appManager ){
            Map<String, Object> result = new HashMap<>();
            result.put("status", CommonResultEnum.AUTH_ERROR.getCode());
            result.put("message", "appid不存在");
            HttpUtil.writeJson(response, new JSONObject(result));
            return false;
        }

        if(requestURI.equals(AppletsApiUrlMapping.USER_CODE_TWO_SESSION_LOGIN)
        || requestURI.equals(AppletsApiUrlMapping.USER_USER_PROFILE_REGIST_OR_LOGIN)
        || requestURI.equals(AppletsApiUrlMapping.SETTING_GET)
                || requestURI.equals(AppletsApiUrlMapping.USER_H5_CODE_GET)
                || "/applets/article/list".equals(requestURI)
                || "/applets/article/info".equals(requestURI)
        ){
            //注册/登录用户
            UserInfoRes userInfoRes = new UserInfoRes();
            userInfoRes.setSource(appManager.getSource());
            userInfoRes.setVersion(ServletUtil.getHeader(UserConstant.V));
            UserAuthContext.setUserLoginInfo(userInfoRes);

            return true;
        }

        String accessToken = ServletUtil.getHeader(UserConstant.MINI_TOKEN);

        //请求token记录
        log.info("minitoken:{}",accessToken);

        StringRedisTemplate redisTemplate = (StringRedisTemplate) ApplicationContextHelper.getBean("stringRedisTemplate");

        if( StrUtil.isEmpty(accessToken) ){
            Map<String, Object> result = new HashMap<>();
            result.put("status", CommonResultEnum.AUTH_ERROR.getCode());
            result.put("message", "认证失败");
            HttpUtil.writeJson(response, new JSONObject(result));
            return false;
        }




        String userinfo =
                redisTemplate.opsForValue().get(RedisKeyAppletsConstant.APPLETS_TOKEN_USER_INFO + accessToken);
        if( StrUtil.isEmpty(userinfo) ){
            Map<String, Object> result = new HashMap<>();
            result.put("status", CommonResultEnum.AUTH_ERROR.getCode());
            result.put("message", "认证失败");
            HttpUtil.writeJson(response, new JSONObject(result));
            return false;
        }

        //注册/登录用户
        UserInfoRes userInfoRes = JSONObject.parseObject(userinfo,UserInfoRes.class);
        userInfoRes.setSource(appManager.getSource());
        userInfoRes.setVersion(ServletUtil.getHeader(UserConstant.V));
        UserAuthContext.setUserLoginInfo(userInfoRes);

        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//
//        HttpSession httpSession = request.getSession();
//        //myBody是在响应的时候写入到Session的key，可以看responseWrapper
//        String result = (String)httpSession.getAttribute("responseBody");
//        log.info("响应参数：{}",result);
    }
}
